package com.eh.proxy.virtual.component;

import com.eh.proxy.virtual.icon.ImageProxy;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;
import java.util.Map;

/**
 * Created by David on 2016/5/3.
 */
public class ImageJFrame extends JFrame {
    private JMenuBar menuBar;
    private JMenu menu;
    private Map<String, String> cds;
    private ImageComponent imageComponent;

    public ImageJFrame() throws HeadlessException {
        this.setTitle("CD代理演示");
        initCDs();
        initMenus();
        initDisplay();
    }

    private void initCDs() {
        cds = new Hashtable<>();
        cds.put("cd1", "https://images-cn.ssl-images-amazon.com/images/I/61TQPhhY-6L.jpg");
        cds.put("cd2", "https://images-cn.ssl-images-amazon.com/images/I/51qHyyCoERL.jpg");
        cds.put("cd3", "https://images-cn.ssl-images-amazon.com/images/I/51pJ9jJikyL.jpg");
        cds.put("cd4", "https://images-cn.ssl-images-amazon.com/images/I/41T3WTJw%2B7L.jpg");
        cds.put("cd5", "https://images-cn.ssl-images-amazon.com/images/I/81lrh%2B4PrHL._SL1280_.jpg");
    }

    private void initMenus() {
        this.menuBar = new JMenuBar();
        menu = new JMenu("最喜欢的CD");
        menuBar.add(menu);
        this.setJMenuBar(menuBar);
        for (Map.Entry<String, String> entry : cds.entrySet()) {
            String name = entry.getKey();
            JMenuItem menuItem = new JMenuItem(name);
            menu.add(menuItem);
            menuItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    imageComponent.setIcon(new ImageProxy(getURL(e.getActionCommand())));
                }
            });
        }
    }

    private URL getURL(String name) {
        try {
            return new URL(cds.get(name));
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void initDisplay() {
        try {
            URL initialURL = new URL(cds.get("cd2"));
            Icon icon = new ImageProxy(initialURL);
            imageComponent = new ImageComponent(icon);
            this.getContentPane().add(imageComponent);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setBounds(400, 200, 800, 600);
            this.setVisible(true);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}
